<template>
    <div class="platform">
        <my-tag title="优惠券管理" :showSortImg="false"></my-tag>
        <div class="platform-box">
            <el-form ref="formRef" :model="form" :rules="rules" label-position="top" label-width="auto"
                class="demo-ruleForm platform-formList">
                <div class="form-left-six">
                    <el-form-item label="优惠券名称" prop="schemeName">
                        <el-input v-model="form.schemeName" placeholder="请输入优惠券名称" @focus="schemeNameLimit = true"
                            @blur="schemeNameLimit = false" :show-word-limit="schemeNameLimit" maxlength="20" />
                    </el-form-item>
                    <el-form-item label="使用说明" prop="designIdea">
                        <el-input type="textarea" :autosize="{ minRows: 4 }" v-model="form.designIdea" placeholder="请输入使用说明"
                            @focus="remarkLimit = true" @blur="remarkLimit = false" :show-word-limit="remarkLimit"
                            maxlength="500" />
                    </el-form-item>
                    <el-form-item label="适用角色">
                        <el-select v-model="form.canalFrom" placeholder="请选择适用角色" @change="canalFromChange">
                            <el-option v-for="item in canalFromSel" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="适用范围">
                        <el-table :data="tableData" style="margin:20px 0;">
                            <el-table-column prop="id" :label="`${name}ID`" align="center" :show-overflow-tooltip="true" />
                            <el-table-column :label="`${name}形象照`" align="center" width="110">
                                <template #default="scope">
                                    <image-preview :width="60" :height="60" :src="scope.row.figureImg"
                                        :preview-src-list="[scope.row.figureImg]"></image-preview>
                                </template>
                            </el-table-column>
                            <el-table-column prop="name" :label="`${name}名称`" align="center"
                                :show-overflow-tooltip="true" />
                            <el-table-column prop="address" :label="`${name}地址`" align="center"
                                :show-overflow-tooltip="true" />
                            <el-table-column label="操作" align="center" width="80">
                                <template #default="scope">
                                    <el-button link type="primary" size="small"
                                        @click="delHandel(scope.$index, scope.row.id, tableData)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="add-room" @click="addCanal">+ 添加{{ name }}</div>
                    </el-form-item>
                </div>
                <div class="form-right-four">
                    <el-form-item label="发放数量" prop="number">
                        <el-input-number style="width:100%;" v-model="form.number" :min="1" :max="999999"
                            controls-position="right" size="default" placeholder="请输入发放数量"></el-input-number>
                    </el-form-item>
                    <el-form-item label="领取时间" prop="getTime">
                        <div>
                            <el-radio-group v-model="form.getTime" size="large">
                                <el-radio-button label="不限时" value="不限时" />
                                <el-radio-button label="限时" value="限时" />
                            </el-radio-group>
                            <el-form-item prop="timeLimit" v-if="form.getTime === '限时'" style="margin-top:20px;">
                                <el-date-picker size="large" v-model="form.timeLimit" type="daterange"
                                    value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始时间"
                                    end-placeholder="结束时间" />
                            </el-form-item>
                        </div>
                    </el-form-item>
                    <el-form-item label="有效日期" prop="activeTime">
                        <div>
                            <el-radio-group v-model="form.activeTime" size="large">
                                <el-radio-button label="天数" value="天数" />
                                <el-radio-button label="时间段" value="时间段" />
                            </el-radio-group>
                            <el-form-item prop="timeLimit" v-if="form.activeTime === '天数'" style="margin-top:20px;">
                                <div style="display: flex;align-items: center;">
                                    <div style="margin-right:4px;">领取当日起</div>
                                    <el-input-number v-model="form.area" :min="1" :max="999999" controls-position="right"
                                        size="default" placeholder="请输入"></el-input-number>
                                    <div style="margin-left:4px;">天可用</div>
                                </div>
                            </el-form-item>
                            <el-form-item prop="timeLimit" v-if="form.activeTime === '时间段'" style="margin-top:20px;">
                                <el-date-picker size="large" v-model="form.timeLimit" type="daterange"
                                    value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始时间"
                                    end-placeholder="结束时间" />
                            </el-form-item>
                        </div>
                    </el-form-item>
                    <el-form-item label="领取限制" prop="restrictions">
                        <el-radio-group v-model="form.restrictions" size="large">
                            <el-radio-button label="不限量" value="不限量" />
                            <el-radio-button label="限量" value="限量" />
                        </el-radio-group>
                        <el-form-item prop="timeLimit" v-if="form.restrictions === '限量'" style="margin-top:20px;">
                            <div style="display: flex;align-items: center;">
                                <div style="margin-right:4px;">每人限领</div>
                                <el-input-number v-model="form.restrictionsNum" :min="1" :max="999999"
                                    controls-position="right" size="default" placeholder="请输入"></el-input-number>
                                <div style="margin-left:4px;">张</div>
                            </div>
                        </el-form-item>
                    </el-form-item>
                    <el-form-item label="是否付费(元)" prop="isPayment">
                        <el-radio-group v-model="form.isPayment" size="large">
                            <el-radio-button label="否" value="否" />
                            <el-radio-button label="是" value="是" />
                        </el-radio-group>
                        <el-form-item prop="money" v-if="form.isPayment === '是'" style="margin-top:20px;width:100%;">
                            <el-input-number style="width:100%;" v-model="form.number" :min="1" :max="999999" :precision="2"
                                controls-position="right" size="default" placeholder="请输入金额"></el-input-number>
                        </el-form-item>
                    </el-form-item>
                </div>
            </el-form>

            <div class="platform-submit-btn">
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button class="default-btn" @click="goBack">返回</el-button>
            </div>
        </div>
        <el-dialog :title="`添加${name}`" v-model="openDialog" width="800" @close="closeDialog">
            <!-- 搜索 -->
            <el-form :model="openDialogQueryParams" ref="queryRef" :inline="true" v-show="showSearch"
                @submit.native.prevent>
                <div class="common-search-form">
                    <el-form-item :label="`${name}名称`" prop="names">
                        <el-input v-model="openDialogQueryParams.names" :placeholder="`请输入${name}名称`" style="width: 260px"
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </div>
            </el-form>
            <!-- 表格 -->
            <el-table v-loading="loading" :data="dialogTable" style="margin:20px 0;" max-height="400" ref="multipleTable"
                row-key="id" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" :reserve-selection="true" :selectable="selectable" />
                <el-table-column prop="id" :label="`${name}ID`" :show-overflow-tooltip="true" align="center" />
                <el-table-column :label="`${name}形象照`" align="center">
                    <template #default="scope">
                        <image-preview :width="60" :height="60" :src="scope.row.figureImg"
                            :preview-src-list="[scope.row.figureImg]"></image-preview>
                    </template>
                </el-table-column>
                <el-table-column prop="name" :label="`${name}名称`" :show-overflow-tooltip="true" align="center" />
                <el-table-column prop="address" :label="`${name}地址`" :show-overflow-tooltip="true" align="center" />
            </el-table>
            <pagination v-show="openDialogTotal > 0" :total="openDialogTotal" v-model:page="openDialogQueryParams.pageNum"
                v-model:limit="openDialogQueryParams.pageSize" @pagination="paginationHandel" />
            <div class="platform-submit-btn">
                <el-button type="primary" @click="confirmDialog">确定</el-button>
                <el-button class="default-btn" @click="closeDialog">关闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script setup>
import { listMaterialSupplier } from "@/api/decor/materialSupplier";
import { listOrganization } from "@/api/decor/designAgency";
import { getImgUrl } from "@/api/decor/designer";
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const remarkLimit = ref(false)
const schemeNameLimit = ref(false)
// 优惠券渠道类型
const canalFromSel = ref([
    { value: 0, label: '材料商' },
    { value: 1, label: '机构' },
    // { value: 2, label: '材料' }
])
let openDialog = ref(false)
const showSearch = ref(true)
const tableData = ref([]) // 优惠券渠道表格
const dialogTable = ref([])  // 弹框表格数据
const openDialogTotal = ref(0)  // 总数
const loading = ref(true)
// 多选框
const selectionData = ref([])
const data = reactive({
    form: {
        canalFrom: 0
    },
    rules: {
        livingRooms: [{ required: true, message: "客厅数量不能为空", trigger: "blur" }],
        bedrooms: [{ required: true, message: "优惠券数量不能为空", trigger: "blur" }],
        bathrooms: [{ required: true, message: "卫生间数量不能为空", trigger: "blur" }],
        kitchens: [{ required: true, message: "厨房数量不能为空", trigger: "blur" }],
        priceUpper: [{ required: true, message: "最高参考预算价不能为空", trigger: "blur" }],
        priceLower: [{ required: true, message: "最低参考预算价不能为空", trigger: "blur" }],
    },
    // 弹框表格搜索
    openDialogQueryParams: {
        pageSize: 2,
        pageNum: 1,
        names: ''
    }
});
const { form, rules, openDialogQueryParams } = toRefs(data);
const name = ref('')
// 下拉框
const canalFromChange = (val) => {
    name.value = val === 1 ? '机构' : '材料商'
    tableData.value = []
    getList()
    nextTick(() => {
        if (proxy.$refs.multipleTable) {
            proxy.$refs.multipleTable.clearSelection()
        }
    })
}
// 搜索
const handleQuery = () => {
    openDialogQueryParams.value.pageNum = 1;
    getList();
}
// 重置
const resetQuery = () => {
    proxy.resetForm("queryRef");
    handleQuery();
}
const selectable = (row) => {
    let _ids = []
    tableData.value.forEach((v) => {
        _ids.push(v.id)
    })
    return !_ids.includes(row.id);
}
// 获取弹框数据信息
const getDataListFn = (API) => {
    API(openDialogQueryParams.value).then(response => {
        let imgUrlPromises = [];
        let data = response.rows.map((v) => {
            return { ...v, avatarImg: '', id: v.organizationId ? v.organizationId : v.materialSupplierId, name: v.organizationName ? v.organizationName : v.materialSupplierName }
        })
        data.forEach((v) => {
            // 获取形象照的异步操作
            if (v.profilePicture) {
                let coverImagePromise = getImgUrl(v.profilePicture).then((res) => {
                    v.figureImg = res.data[0].url;
                });
                imgUrlPromises.push(coverImagePromise);
            }
        })
        // 等待所有的异步操作完成
        Promise.all(imgUrlPromises).then(() => {
            dialogTable.value = data;
            openDialogTotal.value = response.total;
            loading.value = false;
        });

    });
}
function getList() {
    loading.value = true;
    // 获取材料商
    if (form.value.canalFrom === 0) {
        getDataListFn(listMaterialSupplier)
    } else if (form.value.canalFrom === 1) {
        // 获取机构
        getDataListFn(listOrganization)
    }
}

// 多选框选中数据
function handleSelectionChange(selection) {
    selectionData.value = selection
}
// 分页
const paginationHandel = () => {
    getList()
}
// 打开弹框按钮
const addCanal = () => {
    if (form.value.canalFrom != undefined) {
        openDialog.value = true
    } else {
        proxy.$modal.msgError("请先选择优惠券渠道");
    }
}
// 删除优惠券按钮
const delHandel = (index, id, row) => {
    tableData.value.splice(index, 1)
}
// 弹框的确定按钮
const confirmDialog = () => {
    const _data = [...tableData.value, ...selectionData.value]
    tableData.value = Array.from(new Map(_data.map(item => [item.id, item])).values());
    proxy.$refs.multipleTable.clearSelection()
    openDialog.value = false
}
// 关闭弹框
const closeDialog = () => {
    openDialog.value = false
    selectionData.value = []; // 清空选中状态
    resetQuery()
}
// 提交按钮
const submitForm = () => {
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
            if (tableData.value.length > 0) {

            } else {
                proxy.$modal.msgError("请选择适用范围");
            }
        }
    });
}
const goBack = ()=>{
    router.go(-1)
}
getList()
canalFromChange()
</script>
<style lang="scss" scoped>
.hoseType {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    .hoseType-box {
        width: 30%;
        display: flex;
        align-items: center;
        justify-content: flex-start;

        .unit {
            font-family: NotoSansHans, NotoSansHans;
            font-weight: 600;
            font-size: 14px;
            color: #000000;
            line-height: 21px;
            font-style: normal;
            padding: 0 4px 0 4px;
        }
    }
}

.coverImg-style {
    width: 100%;

    ::v-deep(.el-upload-list--picture-card) {
        width: 320px;
        height: 240px;
    }

    ::v-deep(.el-upload--picture-card) {
        width: 320px;
        height: 240px;
    }

    ::v-deep(.el-upload-list--picture-card .el-upload-list__item) {
        width: 320px;
        height: 240px;
        border-radius: 8px;
        border: 1px solid #CDD4E0;
    }

}

::v-deep(.el-checkbox__input.is-disabled .el-checkbox__inner) {
    border-color: transparent;
    background-color: transparent;
}

::v-deep(.el-checkbox__input.is-disabled .el-checkbox__inner::after) {
    box-sizing: content-box;
    content: "";
    border: 1px solid transparent;
    border-left: 0;
    border-top: 0;
    height: 7px;
    left: 4px;
    position: absolute;
    top: 1px;
    transform: rotate(45deg) scaleY(0);
    width: 3px;
    transition: transform .15s ease-in 50ms;
    transform-origin: center;
}
</style>